﻿using System.IO;
using System.Threading;

namespace System
{
    /// <summary>
    /// 一个默认使用文件进行记录的日志器。
    /// </summary>
    public class FileLogger:LoggerBase {
        public override void LogInfo(string message) {
            AppendAllText(message,LogType.Info.ToString());
        }
        public override void LogWarn(string message) {
            AppendAllText(message,LogType.Warn.ToString());
        }
        public override void LogDebug(string message) {
            AppendAllText(message,LogType.Debug.ToString());
        }
        public override void LogTrace(string message) {
            AppendAllText(message,LogType.Trace.ToString());
        }
        public override void LogSql(string message) {
            AppendAllText(message,LogType.Sql.ToString());
        }
        public override void LogError(string title,Exception e) {
            AppendAllText(title + e.ToString(),LogType.Error.ToString());
        }
        public override void LogError(string message) {
            AppendAllText(message,LogType.Error.ToString());
        }
        public override void LogFile(string message,string filename) {
            AppendAllText(message + Environment.NewLine,LogType.Error.ToString());
        }
        private void AppendAllText(string contents,string filename) {
            try {
                if(string.IsNullOrWhiteSpace(contents)) return;

                string msg = string.Format(@"{0}|{1}|" + filename + "|{2}" + Environment.NewLine,DateTime.Now,Thread.CurrentThread.ManagedThreadId,contents);

                object result = null;
                Enum.TryParse(typeof(LogType),filename,out result);
                if(result == null) result = filename;
                string t = "Logs";
                string path = System.IO.Directory.GetCurrentDirectory() + "//" + t;
                string logfile = path + "/" + result.ToString().ToLower() + DateTime.Now.ToString("yyyyMMdd") + ".log";
                if(!Directory.Exists(path)) {
                    Directory.CreateDirectory(path);
                }
                File.AppendAllTextAsync(logfile,msg);
            } catch {

            }
        }
    }
}